﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using System;
using System.Net;

namespace YFurion.Consul
{
    public static class ConsulClientExtensions
    {
        private const string URL_PREFIX = "urlprefix-/";
        public static IApplicationBuilder UseConsulClient(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceEntity serviceEntity)
        {
            ConsulClient consulClient = new ConsulClient(config =>
           config.Address = new Uri($"{serviceEntity.ConsulUrl}"));
            AgentServiceCheck serviceCheck = new AgentServiceCheck
            {
                HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/health",
                Timeout = TimeSpan.FromSeconds(10),
                Interval = TimeSpan.FromSeconds(5),
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
            };
            AgentServiceRegistration serviceRegistration = new AgentServiceRegistration
            {
                Checks = new[] { serviceCheck },
                ID = $"{serviceEntity.Name}{Guid.NewGuid().ToString()}",
                Name = serviceEntity.Name,
                Address = serviceEntity.IP,
                Port = serviceEntity.Port,
                Tags = new[] { $"{URL_PREFIX}{serviceEntity.Name}" } //添加urlprefix-/servicename格式的tag标签，以便识别
            };
            WriteResult result = consulClient.Agent.ServiceRegister(serviceRegistration).GetAwaiter().GetResult();
            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"Consul client[{serviceCheck.HTTP}] registration failed");
            }
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(serviceRegistration.ID).Wait();
            });
            return app;
        }
    }
}
